$(function() {
	var doc = $(document),
		body = $('body'),
		sideContent = body.find('.side-content'),
		preview = body.find('.preview'),
		tabs = body.find('.tabs');
	
		$.widget("MQM.preview", {

			_create: function () {
				var self = this,
					e = self.element;
					
				self.seeds = {};
				e.html(template("preview-tmpl"));
				
				doc.on('seedadded', function (ev, seed) {
					var id = seed.id;
					if (self.seeds[seed.id]) {
						e.find('.seed').each(function (index, element) {
							var eid = $(element).data('id');
							if (eid === id) {
								$(element).parent().questionSeed('draw', seed);
							}
						});
					} else {
						//console.log(seed);
						//e.append(seed.genPreviewHtml());
						self.seeds[seed.id] = seed;
						seeds[seed.id] = seed;
						self.addSeed(seed);
					}
					doc.trigger('questionselect');
				});
			},
			
			addSeed: function (seed) {
				var self = this,
					e = self.element;
					
				e.append($('<div></div>').questionSeed({seed: seed}));
			}
			
			
		});
		
		$.widget("MQM.questionSeed", {
			
			options: {
				seed: null
			},
			
			_create: function () {
				var self = this,
					e = self.element,
					o = self.options;
					
				self.draw();
				
				e.on('click', function () {
					e.trigger('seedselected', o.seed);
				});
				
				self.remove = $('<div class="remove">X</div>');
				e.find('.seed').prepend(self.remove);
				e.on('click', '.remove', function () {
					e.trigger('seedremoved', o.seed.id);
					e.remove();
					delete seeds[o.seed.id];
				});
				
			},
			
			draw: function (seed) {
				var self = this,
					e = self.element,
					o = self.options;
				
				if (seed) {
					o.seed = seed;
					seeds[seed.id] = seed;
				}
				e.html(template(o.seed.type + '-tmpl', o.seed));
				e.find('div').each(function (index,input) {
					$(input).html($(input).html().replace(/\\;/g,';'));
				});
				e.find('.seed').prepend(self.remove);
			},
			
			get: function () {
				var self = this,
					o = self.options;
					
				return o.seed;
			}
			
		});
		
		$.widget("MQM.tabs", {
			_create: function () {
				var self = this;
				
				for (i = 0; i < 10; i++) {
					self.addTab("Test" + i);
				}
				
			},
			
			addTab: function (label) {
				var self = this,
					e = self.element;
					
				var obj = {label: label};
				
				e.append(template('tab-tmpl', obj));
			}
		});
		
		preview.preview();
		//tabs.tabs();
});